package com.longtop.framework.sys.flow.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.Constant;
import com.longtop.framework.common.QueryConditions;
import com.longtop.framework.common.QueryResult;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.sys.flow.model.TSysFlowTeam;
import com.longtop.framework.sys.user.model.TSysUser;
import com.longtop.framework.util.StringUtil;

/**
 * 
 * @author 杨向阳
 * 
 */

public class FlowTeamService extends BaseService {
	public static final String BEAN_ID = "flowTeamService";

	/**
	 * 保存、修改、删除一起做！
	 * 
	 * @param changeMap
	 *            对象列表，有三个值，删除主键列表、更新bean的列表、新增bean的列表
	 * @param sessionObject
	 * @return 操作成功受影响的记录数，有三个值，插入成功的记录数、更新成功的记录数、删除成功的记录数
	 */
	public Integer[] saveTeam(Map changeMap, SessionObject sessionObject) throws BaseCheckedException {

		// 插入成功的记录数、更新成功的记录数、删除成功的记录数
		int insertCount = 0;
		int updateCount = 0;
		int deleteCount = 0;

		// 删除主键列表、更新bean的列表、新增bean的列表
		List insertBeanList = (ArrayList) changeMap.get(Constant.INSERT_BEAN_LIST);
		List updateBeanList = (ArrayList) changeMap.get(Constant.UPDATE_BEAN_LIST);
		String idList = (String) changeMap.get(Constant.ID_LIST);

		TSysFlowTeam tSysFlowTeam;
		Iterator iterator;

		// 批量插入记录
		if (insertBeanList.size() > 0) {
			iterator = insertBeanList.iterator();
			while (iterator.hasNext()) {
				tSysFlowTeam = (TSysFlowTeam) iterator.next();
				// 校验id是否重复。
				if (isExistTeamId(tSysFlowTeam.getTeamId()))
					throw new BaseCheckedException("", "保存失败,流程用户组id【" + tSysFlowTeam.getTeamId() + "】已经存在!");
				String users[] = this.getTeamUserByUserIdList(tSysFlowTeam.getUserIdList());
				String userIdList = users[0];
				String userNameList = users[1];
				tSysFlowTeam.setUserIdList(userIdList);
				tSysFlowTeam.setUserNameList(userNameList);
				super.save(tSysFlowTeam);
				insertCount++;
			}
		}

		// 批量更新记录
		if (updateBeanList.size() > 0) {
			iterator = updateBeanList.iterator();
			while (iterator.hasNext()) {
				tSysFlowTeam = (TSysFlowTeam) iterator.next();
				String users[] = this.getTeamUserByUserIdList(tSysFlowTeam.getUserIdList());
				String userIdList = users[0];
				String userNameList = users[1];
				tSysFlowTeam.setUserIdList(userIdList);
				tSysFlowTeam.setUserNameList(userNameList);
				super.update(tSysFlowTeam);
				updateCount++;
			}
		}

		// 批量删除记录
		if (idList.length() > 0) {
			String sql = "delete from TSysFlowTeam where teamId in(" + idList + ")";
			deleteCount = super.batchUpdate(sql);
		}

		return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
	}

	/**
	 * 依据条件，读取流程用户组列表
	 * 
	 * @param queryConditions
	 *            查询条件
	 * @param pageNo
	 *            查询结果的起始页码。
	 * @param pageSize
	 *            查询结果的最大行数。如果不需要，则设置为-1
	 * @return
	 */
	public QueryResult loadTeam(QueryConditions queryConditions, int pageNo, int pageSize) {
		String hql = "from TSysFlowTeam";
		String orderBy = "teamId asc";
		String[] propertyNames = null;
		String[] operators = null;
		Object[] values = null;

		if (queryConditions != null) {
			propertyNames = StringUtil.listToStrArray(queryConditions.getPropertyNames());
			operators = StringUtil.listToStrArray(queryConditions.getOperators());
			List valuesList = queryConditions.getValues();

			if (valuesList != null || valuesList.size() > 0)
				values = valuesList.toArray();
		}

		int offset = (pageNo - 1) * pageSize;

		// 执行查询
		Object[] result = this.query(hql, propertyNames, operators, values, offset, pageSize, true, orderBy, null, null);

		return new QueryResult((List) result[0], result[1] != null ? ((Integer) result[1]).intValue() : 0);
	}

	/**
	 * 通过idlist 得到用户姓名, 剔除重复
	 * 
	 * @param userIdList
	 * @return
	 */
	private String[] getTeamUserByUserIdList(String userIds) {
		String userIdList = "";
		String userNameList = "";

		String[] userSetIds = userIds.trim().split(",");
		for (int i = 0; i < userSetIds.length; i++) {
			String userId = userSetIds[i];
			TSysUser sysUser = this.get(TSysUser.class, userId);
			if (sysUser != null) {
				if (StringUtils.isEmpty(userIdList)) {
					userIdList += userId;
					userNameList += sysUser.getUserName();
				} else {
					userIdList += "," + userId;
					userNameList += "," + sysUser.getUserName();
				}
			}
		}
		
		return new String[] { userIdList, userNameList };
	}

	/**
	 * 验证此 分组 Id 是否存在
	 * 
	 * @param menuId
	 * @return
	 */
	private boolean isExistTeamId(String teamId) {
		boolean flag = false;

		List list = this.queryAll("from TSysFlowTeam where teamId='" + teamId + "'");

		if (list.size() > 0)
			flag = true;

		return flag;
	}
}